package com.ruoyi.system.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.WxPayKit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.pay.WxPayXiaoChengXuConfig;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.Dto.JiajiaMallOrderDto;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.JiajiaMallOrderVo;
import com.ruoyi.system.domain.vo.TransferBillsVo;
import com.ruoyi.system.domain.vo.TransferSceneReportInfo;
import com.ruoyi.system.mapper.JiajiaOrderSeparateAccountsMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.AesUtil;
import com.ruoyi.system.utils.TokenUtil;
import com.ruoyi.system.utils.V3PayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;


@Service
public class ApiPayNotifyServiceImpl implements  ApiPayNotifyService{

    private static final Logger logger = LoggerFactory.getLogger(ApiPayNotifyServiceImpl.class);

    @Autowired
    private IJiajiaOrderService orderService;
    @Resource
    private  ApiPayService apiPayService;
    @Autowired
    private IJiajiaUserMoneyChangeService moneyChangeService;

    @Autowired
    private IJiajiaPointsFlowService iJiajiaPointsFlowService;
    @Autowired
    private IJiajiaAppraiseService appraiseService;

    @Autowired
    private IJiajiaUserService userService;

    @Autowired
    private IJiajiaTransferAccountsService jiajiaTransferAccountsService;

    @Autowired
    private IJiajiaMessageService messageService;

    @Autowired
    private IJiajiaOrderTimeService orderTimeService;

    @Autowired
    private WxPayXiaoChengXuConfig xiaoChengXuConfig;

    @Autowired
    private IJiajiaChongzhiService jiajiaChongzhiService;
    @Autowired
    private IJiajiaChongzhiRecordService jiajiaChongzhiRecordService;

    @Autowired
    private IJiajiaMallOrderService mallOrderService;

    @Autowired
    private IJiajiaMailOrderDetailService iJiajiaMailOrderDetailService;

    @Autowired
    private IJiajiaProxyApplicationService iJiajiaProxyApplicationService;


    @Autowired
    private IJiajiaPointsFlowUserdService jiajiaPointsFlowUserdService;
    @Resource
    private JiajiaOrderSeparateAccountsMapper jiajiaOrderSeparateAccountsMapper;
    /**
     * 微信小程序支付回调接口
     */
    public Map<String, String> wxItemPayNotice(@RequestBody String xmlData)  {
        Map<String, String> map = new HashMap<>();
        System.out.println("微信小程序回调开始了");
        //这里我只进行了部分回调信息的保存，更多参数请查看微信支付官方api:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlData);
        /*----------------------分割线，下面的是业务代码，根据自己业务进行修改--------------------------*/
        //订单成功业务处理
        if ("SUCCESS".equals(resultMap.get("result_code"))) {
            //订单号
            String nonce_str = resultMap.get("out_trade_no");

            JiajiaOrder order = new JiajiaOrder();
            order.setOrderSn(nonce_str);
            List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);
            if (orderList.isEmpty()){
                return map;
            }
            order = orderList.get(0);
            //已经支付过的不再处理回调
            if (order.getStatus().intValue() != 0 || order.getPayStatus().intValue() == 1){
                return map;
            }
            String totalFee = resultMap.get("total_fee");

            BigDecimal payAmount = BigDecimal.ZERO;
            if(StringUtils.isNotEmpty(totalFee)){
                payAmount = BigDecimal.valueOf(Double.valueOf(totalFee)).divide(BigDecimal.valueOf(100)
                        .setScale(2, RoundingMode.HALF_UP));
            }
            String transactionId = resultMap.get("transaction_id");
            order.setTransactionId(transactionId);
            orderService.updateJiajiaOrder(order);
            JiajiaUser user = userService.selectJiajiaUserById(order.getUid());
            if (user == null){
                return map;
            }
            order.setStatus(1);

            //创建通知
            JiajiaMessage message = new JiajiaMessage();
            message.setType(1);
            message.setTitle("客户已下单");
            message.setContent("请尽快接单");
            message.setUid(order.getWid());
            messageService.insertJiajiaMessage(message);

            //创建通知
            JiajiaMessage userMessage = new JiajiaMessage();
            userMessage.setType(2);
            userMessage.setTitle("下单成功");
            userMessage.setContent("下单成功,等待社工接单!");
            userMessage.setUid(user.getId());
            messageService.insertJiajiaMessage(userMessage);

            order.setPaytime(new Date());
            order.setPayStatus(1);
            orderService.updateJiajiaOrder(order);

            System.out.println("执行具体业务完毕");
        }
        /*----------------------分割线，业务结束--------------------------*/

        map.put("return_code", "SUCCESS");
        map.put("return_msg", "OK");
        return map;
    }


    /**
     * 微信商城支付回调接口
     */
    @PostMapping("/wxMallPayNotice")
    public Map<String, String> wxMallPayNotice(@RequestBody String xmlData)  {
        Map<String, String> map = new HashMap<>();
        System.out.println("微信商城支付回调接口");
        //这里我只进行了部分回调信息的保存，更多参数请查看微信支付官方api:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlData);
        /*----------------------分割线，下面的是业务代码，根据自己业务进行修改--------------------------*/
        //订单成功业务处理
        if ("SUCCESS".equals(resultMap.get("result_code"))) {
            //订单号
            String nonce_str = resultMap.get("out_trade_no");
            JiajiaMallOrderDto jiajiaMallOrder=new JiajiaMallOrderDto();
            jiajiaMallOrder.setOrderNum(nonce_str);
            List<JiajiaMallOrderVo> jiajiaMallOrders = mallOrderService.selectJiajiaMallOrderList(jiajiaMallOrder);
            JiajiaMallOrderVo jiajiaMallOrderResult = jiajiaMallOrders.get(0);
            //已经支付过的不再处理回调
            if (jiajiaMallOrderResult.getOrderStatus() .equals("0")){
                String transactionId = resultMap.get("transaction_id");
                jiajiaMallOrderResult.setTransactionId(transactionId);
                jiajiaMallOrderResult.setOrderStatus("2");
                JiajiaMallOrder jiajiaMallOrder1 = new JiajiaMallOrder();
                BeanUtils.copyProperties(jiajiaMallOrderResult,jiajiaMallOrder1);
                mallOrderService.updateJiajiaMallOrder(jiajiaMallOrder1);
                //把已用积分写入积分流水表
                jiajiaPointsFlowUserdService.saveJiajiaPointsFlowUserds(jiajiaMallOrder1);
            }
        }
        /*----------------------分割线，业务结束--------------------------*/
        return map;
    }

    @Override
    @Transactional
    public Map<String, String> wxProxyPayNotice(String xmlData) {
        Map<String, String> map = new HashMap<>();
        synchronized (xmlData){
            System.out.println("微信小程序回调开始了");
            //这里我只进行了部分回调信息的保存，更多参数请查看微信支付官方api:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
            Map<String, String> resultMap = WxPayKit.xmlToMap(xmlData);
            /*----------------------分割线，下面的是业务代码，根据自己业务进行修改--------------------------*/
            //订单成功业务处理
            if ("SUCCESS".equals(resultMap.get("result_code"))) {
                //订单号
                String nonce_str = resultMap.get("out_trade_no");

                JiajiaProxyApplication jiajiaProxyApplication = iJiajiaProxyApplicationService.selectJiajiaProxyApplicationById(Long.valueOf(nonce_str));//已经支付过的不再处理回调

                if (jiajiaProxyApplication.getTransactionId() !=null){
                    return map;
                }

                String transactionId = resultMap.get("transaction_id");
                jiajiaProxyApplication.setTransactionId(transactionId);
                iJiajiaProxyApplicationService.updateJiajiaProxyApplication(jiajiaProxyApplication);
                if (jiajiaProxyApplication.getType().equals(0) || jiajiaProxyApplication.getType()==0) {
                    //自动审核通过
                    jiajiaProxyApplication.setStatus(1);
                    iJiajiaProxyApplicationService.updateJiajiaProxyApplication(jiajiaProxyApplication);
                    //申请人
                    JiajiaUser jiajiaUser = userService.selectJiajiaUserById(jiajiaProxyApplication.getUserId());
                    //收益人
                    JiajiaUser jiajiaUser1 = userService.selectBeneficiary(jiajiaUser);
                    BigDecimal money = jiajiaUser1.getMoney();
                    String income = CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY + SysConfigConstants.sys_promotion_promoter).toString();
                    BigDecimal incomeAfter = money.add(new BigDecimal(income));
                    jiajiaUser1.setMoney(incomeAfter);
                    userService.updateJiajiaUser(jiajiaUser1);
                    //加入流水表
                    JiajiaTransferAccounts jiajiaTransferAccounts=new JiajiaTransferAccounts();
                    jiajiaTransferAccounts.setUserId(jiajiaUser1.getId());
                    jiajiaTransferAccounts.setTransferAmount(new BigDecimal(income));
                    jiajiaTransferAccounts.setOrderId(jiajiaProxyApplication.getId());
                    jiajiaTransferAccounts.setSourceUserId(jiajiaUser.getId());
                    jiajiaTransferAccounts.setOrderType("1");
                    jiajiaTransferAccounts.setTransferType("4");
                    jiajiaTransferAccounts.setRemark("推广推广员收益");
                    jiajiaTransferAccounts.setVersion(LocalDateTime.now()+String.valueOf(Math.random()));
                    jiajiaTransferAccounts.setDeleted("1");
                    jiajiaTransferAccountsService.insertJiajiaTransferAccounts(jiajiaTransferAccounts);

                }
                System.out.println("执行具体业务完毕");
            }
            /*----------------------分割线，业务结束--------------------------*/

            map.put("return_code", "SUCCESS");
            map.put("return_msg", "OK");
            return map;
        }

    }





    /**
     * 退款通知
     */
    @RequestMapping(value = "/refundNotify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String refundNotify(HttpServletRequest request) {
        logger.info("退款进入回调");
        String xmlMsg = HttpKit.readData(request);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);

        String returnCode = params.get("return_code");
        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        if (WxPayKit.codeIsOk(returnCode)) {
            String reqInfo = params.get("req_info");
            String decryptData = WxPayKit.decryptData(reqInfo, xiaoChengXuConfig.getMckKey());
            // 更新订单信息
            logger.info("xmlMsg： "+xmlMsg);
            // 发送通知等
            Map<String, String> xml = new HashMap<String, String>(2);
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            return WxPayKit.toXml(xml);
        }
        return null;
    }

    /**
     * 微信小程序充值回调接口
     */
    @PostMapping("/wxmallPayChongZhiNotice")
    public Map<String, String> wxmallPayChongZhiNotice(@RequestBody String xmlData)  {
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("微信小程序回调开始了");
        //这里我只进行了部分回调信息的保存，更多参数请查看微信支付官方api:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlData);
        /*----------------------分割线，下面的是业务代码，根据自己业务进行修改--------------------------*/
        //订单成功业务处理
        if ("SUCCESS".equals(resultMap.get("result_code"))) {
            //订单号
            String nonce_str = resultMap.get("out_trade_no");

            JiajiaChongzhiRecord record = new JiajiaChongzhiRecord();
            record.setChongZhiSn(nonce_str);
            List<JiajiaChongzhiRecord> recordList = jiajiaChongzhiRecordService.selectJiajiaChongzhiRecordList(record);
            if (recordList.isEmpty())return map;
            record = recordList.get(0);
            if (record.getStatus().intValue() == 1)return map;

            JiajiaUser user = userService.selectJiajiaUserById(record.getUid());
            if (user == null) return map;

            //计算
            BigDecimal allMoney = record.getChongZhi().add(record.getZengSong());
            BigDecimal beforeMoney = user.getMoney();
            BigDecimal afterMoney = user.getMoney().add(allMoney);

            //保存充值记录
            record.setBeforeMoney(beforeMoney);
            record.setAfterMoney(afterMoney);
            record.setStatus(1);
            jiajiaChongzhiRecordService.updateJiajiaChongzhiRecord(record);

            JiajiaUserMoneyChange moneyChange = new JiajiaUserMoneyChange();
            moneyChange.setChangeBefore(beforeMoney);

            //保存余额至用户
            user.setMoney(afterMoney);
            userService.updateJiajiaUser(user);

            moneyChange.setChangeAfter(afterMoney);
            moneyChange.setChangeMoney(allMoney);
            moneyChange.setType("充值");
            moneyChange.setDes("用户充值"+record.getChongZhi().setScale(2, RoundingMode.HALF_UP)+"元，赠送"+record.getZengSong().setScale(2,RoundingMode.HALF_UP)+"元");
            moneyChange.setOtherId(record.getId().toString());
            moneyChange.setUid(record.getUid());
            moneyChangeService.insertJiajiaUserMoneyChange(moneyChange);

            JiajiaMessage message = new JiajiaMessage();
            message.setTitle("充值成功");
            message.setContent("充值金额:"+record.getChongZhi().setScale(2,RoundingMode.HALF_UP)+"元，赠送"+record.getZengSong().setScale(2,RoundingMode.HALF_UP)+"元");
            message.setType(2);
            message.setUid(user.getId());
            messageService.insertJiajiaMessage(message);


            System.out.println("执行具体业务完毕");
        }
        /*----------------------分割线，业务结束--------------------------*/

        map.put("return_code", "SUCCESS");
        map.put("return_msg", "OK");
        return map;
    }


    /**
     * 微信支付回调接口
     */
    @PostMapping("/wxPayNotice")
    public Map<String, String> wxPayNotice(@RequestBody String xmlData)  {
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("微信回调开始了");
        //这里我只进行了部分回调信息的保存，更多参数请查看微信支付官方api:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlData);
        /*----------------------分割线，下面的是业务代码，根据自己业务进行修改--------------------------*/
        //订单成功业务处理
        if ("SUCCESS".equals(resultMap.get("result_code"))) {
            //订单号
            String nonce_str = resultMap.get("out_trade_no");

            JiajiaOrder order = new JiajiaOrder();
            order.setOrderSn(nonce_str);
            List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);
            if (orderList.isEmpty()){
                return map;
            }
            order = orderList.get(0);

            if (order.getStatus().intValue() != 0){
                return map;
            }

            JiajiaUser user = userService.selectJiajiaUserById(order.getUid());
            if (user == null){
                return map;
            }
            order.setStatus(1);

            //创建通知
            JiajiaMessage message = new JiajiaMessage();
            message.setType(1);
            message.setTitle("客户已下单");
            message.setContent("请尽快接单");
            message.setUid(order.getWid());
            messageService.insertJiajiaMessage(message);

            //创建通知
            JiajiaMessage userMessage = new JiajiaMessage();
            userMessage.setType(2);
            userMessage.setTitle("下单成功");
            userMessage.setContent("下单成功,等待社工接单!");
            userMessage.setUid(user.getId());
            messageService.insertJiajiaMessage(userMessage);

            order.setPaytime(new Date());
            order.setPayStatus(1);
            orderService.updateJiajiaOrder(order);

            System.out.println("执行具体业务完毕");
        }
        /*----------------------分割线，业务结束--------------------------*/

        map.put("return_code", "SUCCESS");
        map.put("return_msg", "OK");
        return map;
    }

    /**
     * 退款通知
     */
    @RequestMapping(value = "/wxRefundNotify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String wxRefundNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);

        String returnCode = params.get("return_code");
        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        if (WxPayKit.codeIsOk(returnCode)) {
            String reqInfo = params.get("req_info");
            String decryptData = WxPayKit.decryptData(reqInfo, xiaoChengXuConfig.getMckKey());
            // 更新订单信息

            // 发送通知等
            Map<String, String> xml = new HashMap<String, String>(2);
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            return WxPayKit.toXml(xml);
        }
        return null;
    }

    /**
     * 微信充值回调接口
     */
    @PostMapping("/wxPayChongZhiNotice")
    public Map<String, String> wxPayChongZhiNotice(@RequestBody String xmlData)  {
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("微信小程序回调开始了");
        //这里我只进行了部分回调信息的保存，更多参数请查看微信支付官方api:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8
        Map<String, String> resultMap = WxPayKit.xmlToMap(xmlData);
        /*----------------------分割线，下面的是业务代码，根据自己业务进行修改--------------------------*/
        //订单成功业务处理
        if ("SUCCESS".equals(resultMap.get("result_code"))) {
            //订单号
            String nonce_str = resultMap.get("out_trade_no");

            JiajiaChongzhiRecord record = new JiajiaChongzhiRecord();
            record.setChongZhiSn(nonce_str);
            List<JiajiaChongzhiRecord> recordList = jiajiaChongzhiRecordService.selectJiajiaChongzhiRecordList(record);
            if (recordList.isEmpty())return map;
            record = recordList.get(0);
            if (record.getStatus().intValue() == 1)return map;

            JiajiaUser user = userService.selectJiajiaUserById(record.getUid());
            if (user == null) return map;

            //计算
            BigDecimal allMoney = record.getChongZhi().add(record.getZengSong());
            BigDecimal beforeMoney = user.getMoney();
            BigDecimal afterMoney = user.getMoney().add(allMoney);

            //保存充值记录
            record.setBeforeMoney(beforeMoney);
            record.setAfterMoney(afterMoney);
            record.setStatus(1);
            jiajiaChongzhiRecordService.updateJiajiaChongzhiRecord(record);

            JiajiaUserMoneyChange moneyChange = new JiajiaUserMoneyChange();
            moneyChange.setChangeBefore(beforeMoney);

            //保存余额至用户
            user.setMoney(afterMoney);
            userService.updateJiajiaUser(user);

            moneyChange.setChangeAfter(afterMoney);
            moneyChange.setChangeMoney(allMoney);
            moneyChange.setType("充值");
            moneyChange.setDes("用户充值"+record.getChongZhi().setScale(2, RoundingMode.HALF_UP)+"元，赠送"+record.getZengSong().setScale(2,RoundingMode.HALF_UP)+"元");
            moneyChange.setOtherId(record.getId().toString());
            moneyChange.setUid(record.getUid());
            moneyChangeService.insertJiajiaUserMoneyChange(moneyChange);

            JiajiaMessage message = new JiajiaMessage();
            message.setTitle("充值成功");
            message.setContent("充值金额:"+record.getChongZhi().setScale(2,RoundingMode.HALF_UP)+"元，赠送"+record.getZengSong().setScale(2,RoundingMode.HALF_UP)+"元");
            message.setType(2);
            message.setUid(user.getId());
            messageService.insertJiajiaMessage(message);


            System.out.println("执行具体业务完毕");
        }
        /*----------------------分割线，业务结束--------------------------*/

        map.put("return_code", "SUCCESS");
        map.put("return_msg", "OK");
        return map;
    }


    //alipay异步通知调用地址 支付宝支付订单回调
    @PostMapping("/aliAppPayNotify")
    @Transactional
    public String aliAppPayNotify(HttpServletRequest request) {
        System.out.println("执行了支付支付成功回调");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values =  requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = false;//调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params,
                    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjKAfHxCHiGgBMZdZQlfjsXj3s5/xYevKjGMnkLI5+JqRVGlDi6GSyMM15r80uZ112BHQgjrm0O/AFrDA6BttOzSVKK+8biicwBXHs2SytPfq2FyZIAAaMaPHB527UFK5I4XmMRycLR1nwPiWL/y9PWOYtwTRJIpG2CpCV0ypZz+Bebf9IdrN3WQPpCUdS3RUDr4PDa1WiYCuycb9txywCEkSaBsf+9xRzxX0SQFgJDhKnGR3JRPBUN+W1KdS0j2Bpev6p9Ew+X28QTlYig6asuPVyZKyZKD33xYqOuIwIijDXYkNTWRsGFpO0fU+EkAQ8F01seei+/rZTO4gJ1kZ0QIDAQAB",
                    "utf-8",
                    "RSA2" );
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(signVerified){
            //商户订单号
            String out_trade_no = null;
            try {
                out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //付款金额，这里获取到三个参数就可以了，后面逻辑代码自己创作
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("回调单号："+out_trade_no);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            //订单号
            String nonce_str = out_trade_no;
            JiajiaOrder order = new JiajiaOrder();
            order.setOrderSn(nonce_str);
            List<JiajiaOrder> orderList = orderService.selectJiajiaOrderList(order);
            if (orderList.isEmpty()){
                return "失败";
            }
            order = orderList.get(0);

            if (order.getStatus().intValue() != 0){
                return "失败";
            }

            JiajiaUser user = userService.selectJiajiaUserById(order.getUid());
            if (user == null){
                return "失败";
            }
            order.setStatus(1);

            //创建通知
            JiajiaMessage message = new JiajiaMessage();
            message.setType(1);
            message.setTitle("客户已下单");
            message.setContent("请尽快接单");
            message.setUid(order.getWid());
            messageService.insertJiajiaMessage(message);

            //创建通知
            JiajiaMessage userMessage = new JiajiaMessage();
            userMessage.setType(2);
            userMessage.setTitle("下单成功");
            userMessage.setContent("下单成功,等待社工接单!");
            userMessage.setUid(user.getId());
            messageService.insertJiajiaMessage(userMessage);

            order.setPaytime(new Date());
            order.setPayStatus(1);
            orderService.updateJiajiaOrder(order);

            return "成功";
        }else{

            return "失败";
        }


    }


    //alipay异步通知调用地址 支付宝充值回调
    @PostMapping("/aliAppPayChongZhiNotify")
    @Transactional
    public String aliAppPayChongZhiNotify(HttpServletRequest request) {
        System.out.println("执行了支付支付成功回调");
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values =  requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = false;//调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params,
                    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjKAfHxCHiGgBMZdZQlfjsXj3s5/xYevKjGMnkLI5+JqRVGlDi6GSyMM15r80uZ112BHQgjrm0O/AFrDA6BttOzSVKK+8biicwBXHs2SytPfq2FyZIAAaMaPHB527UFK5I4XmMRycLR1nwPiWL/y9PWOYtwTRJIpG2CpCV0ypZz+Bebf9IdrN3WQPpCUdS3RUDr4PDa1WiYCuycb9txywCEkSaBsf+9xRzxX0SQFgJDhKnGR3JRPBUN+W1KdS0j2Bpev6p9Ew+X28QTlYig6asuPVyZKyZKD33xYqOuIwIijDXYkNTWRsGFpO0fU+EkAQ8F01seei+/rZTO4gJ1kZ0QIDAQAB",
                    "utf-8",
                    "RSA2" );
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(signVerified){
            //商户订单号
            String out_trade_no = null;
            try {
                out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //付款金额，这里获取到三个参数就可以了，后面逻辑代码自己创作
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("回调单号："+out_trade_no);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
            //订单号
            String nonce_str = out_trade_no;

            JiajiaChongzhiRecord record = new JiajiaChongzhiRecord();
            record.setChongZhiSn(nonce_str);
            List<JiajiaChongzhiRecord> recordList = jiajiaChongzhiRecordService.selectJiajiaChongzhiRecordList(record);
            if (recordList.isEmpty())return "失败";
            record = recordList.get(0);
            if (record.getStatus().intValue() == 1)return "失败";

            JiajiaUser user = userService.selectJiajiaUserById(record.getUid());
            if (user == null) return "失败";

            //计算
            BigDecimal allMoney = record.getChongZhi().add(record.getZengSong());
            BigDecimal beforeMoney = user.getMoney();
            BigDecimal afterMoney = user.getMoney().add(allMoney);

            //保存充值记录
            record.setBeforeMoney(beforeMoney);
            record.setAfterMoney(afterMoney);
            record.setStatus(1);
            jiajiaChongzhiRecordService.updateJiajiaChongzhiRecord(record);

            JiajiaUserMoneyChange moneyChange = new JiajiaUserMoneyChange();
            moneyChange.setChangeBefore(beforeMoney);

            //保存余额至用户
            user.setMoney(afterMoney);
            userService.updateJiajiaUser(user);

            moneyChange.setChangeAfter(afterMoney);
            moneyChange.setChangeMoney(allMoney);
            moneyChange.setType("充值");
            moneyChange.setDes("用户充值"+record.getChongZhi().setScale(2, RoundingMode.HALF_UP)+"元，赠送"+record.getZengSong().setScale(2,RoundingMode.HALF_UP)+"元");
            moneyChange.setOtherId(record.getId().toString());
            moneyChange.setUid(record.getUid());
            moneyChangeService.insertJiajiaUserMoneyChange(moneyChange);

            JiajiaMessage message = new JiajiaMessage();
            message.setTitle("充值成功");
            message.setContent("充值金额:"+record.getChongZhi().setScale(2,RoundingMode.HALF_UP)+"元，赠送"+record.getZengSong().setScale(2,RoundingMode.HALF_UP)+"元");
            message.setType(2);
            message.setUid(user.getId());
            messageService.insertJiajiaMessage(message);


            return "成功";
        }else{

            return "失败";
        }


    }

    @Override
    public String mallRefundNotify(HttpServletRequest request) {
        String xmlMsg = HttpKit.readData(request);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);

        String returnCode = params.get("return_code");
        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        if (WxPayKit.codeIsOk(returnCode)) {
            String reqInfo = params.get("req_info");
            String decryptData = WxPayKit.decryptData(reqInfo, xiaoChengXuConfig.getMckKey());
            // 更新订单信息

            // 发送通知等
            Map<String, String> xml = new HashMap<String, String>(2);
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            return WxPayKit.toXml(xml);
        }
        return null;    }

    @Override
    public String batchTransferNotice(HttpServletRequest request) {
        logger.info("转账进入回调");
        String xmlMsg = HttpKit.readData(request);
        logger.info("回调:"+xmlMsg);
        JSONObject jsonObject = JSONObject.parseObject(xmlMsg);

        logger.info("回调ciphertext:"+jsonObject.get("ciphertext"));
        logger.info("回调associated_data:"+jsonObject.get("associated_data"));
        logger.info("回调nonce:"+jsonObject.get("nonce"));
        AesUtil aesUtil=new AesUtil(V3PayUtil.apiV3Key.getBytes());

        try {
            String s = aesUtil.decryptToString(jsonObject.getString("associated_data").getBytes(), jsonObject.getString("nonce").getBytes(), jsonObject.getString("ciphertext"));
            logger.info("回调参数解析:"+s);

        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }



        return null;
    }
    @Override
    public void transferAccounts(JiajiaUser jiajiaUser,JiajiaProxyApplication jiajiaProxyApplication){
            String inviter=jiajiaUser.getInviter();
            Long sourceUserId=jiajiaUser.getId();
            //分账计数标志
            int count=0;
            //循环标志
            boolean flag=true;
            List<TransferBillsVo> listTransferBillsVo=new ArrayList<>();
            while(flag){
                if(Optional.ofNullable(inviter).isPresent() && !inviter.equals("")){
                    JiajiaUser inviterUser= userService.selectjiajiaUser(inviter);
                    if(apiPayService.isOrdinary(inviterUser)){
                        TransferBillsVo transferBillsVo=new TransferBillsVo();
                        //转账唯一号
                        transferBillsVo.setOutBillNo(WxPayKit.generateStr());
                        //转账金额
                        Integer transferAmount=0;
                        //转账备注
                        String  transferRemark="";
                        TransferSceneReportInfo transferSceneReportInfo1=new TransferSceneReportInfo();

                        if(count == 0 ){
                            if(jiajiaProxyApplication.getType()== 0){
                                transferAmount = Integer.valueOf(CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+ SysConfigConstants.sys_promotion_promoter).toString());
                                transferBillsVo.setTransferType("4");
                            }else{
                                transferAmount = Integer.valueOf(CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+ SysConfigConstants.sys_promotion_community_agent).toString());
                                transferBillsVo.setTransferType("3");
                            }
                            transferRemark="一级推广奖励";

                        }else{
                            if(jiajiaProxyApplication.getType()== 0) {
                                transferAmount = Integer.valueOf(CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+ SysConfigConstants.sys_promotion_promoter_two).toString());

                            }else{
                                transferAmount = Integer.valueOf(CacheUtils.get(Constants.SYS_CONFIG_CACHE, Constants.SYS_CONFIG_KEY+ SysConfigConstants.sys_promotion_community_agent_two).toString());

                            }
                            transferRemark="二级推广奖励";
                            transferBillsVo.setTransferType("8");

                        }

                        //转账金额
                        transferBillsVo.setTransferAmount(transferAmount);
                        //转账备注
                        transferBillsVo.setTransferRemark(transferRemark);
                        //转账场景报备
                        List<TransferSceneReportInfo> list=new ArrayList<>();
                        TransferSceneReportInfo transferSceneReportInfo=new TransferSceneReportInfo();
                        transferSceneReportInfo.setInfoType("活动名称");
                        transferSceneReportInfo.setInfoContent("推广有奖");

                        transferSceneReportInfo1.setInfoType("奖励说明");
                        transferSceneReportInfo1.setInfoContent("推广一次性现金奖励");
                        list.add(transferSceneReportInfo);
                        list.add(transferSceneReportInfo1);
                        transferBillsVo.setTransferSceneReportInfos(list);
                        transferBillsVo.setSourceUserId(sourceUserId);
                        transferBillsVo.setOrderId(jiajiaProxyApplication.getId());
                        transferBillsVo.setOrderType("1");
                        transferBillsVo.setUserId(inviterUser.getId());
                        //转账用户
                        String openId="";
                        if(Optional.ofNullable(inviterUser.getOpenId()).isPresent() && !inviterUser.getOpenId().equals("")){
                            openId=inviterUser.getOpenId();
                            transferBillsVo.setPaymentChannels(TokenUtil.platforms_MP);

                        }else if(Optional.ofNullable(inviterUser.getGzhOpenId()).isPresent()&& !inviterUser.getGzhOpenId().equals("")){
                            openId=inviterUser.getGzhOpenId();
                            transferBillsVo.setPaymentChannels(TokenUtil.platforms_H5);


                        }else{
                            openId=inviterUser.getAppOpenId();
                            transferBillsVo.setPaymentChannels(TokenUtil.platforms_APP);


                        }
                        transferBillsVo.setOpenid(openId);
                        inviter=inviterUser.getInviter();
                        count++;
                        if(count>1){
                            flag=false;
                        }
                        listTransferBillsVo.add(transferBillsVo);
                        sourceUserId=inviterUser.getId();
                    }else {
                        inviter=inviterUser.getInviter();
                        sourceUserId=inviterUser.getId();
                    }

                }else{
                    //推荐人链路断裂
                    flag=false;
                }
            }
            //转账数据准备就位 开始转账
            listTransferBillsVo.stream().forEach(transferBillsVo -> {
                if(transferBillsVo.getTransferAmount()>20000){
                    TransferBillsVo transferBillsVo1 = new TransferBillsVo();
                     BeanUtils.copyProperties(transferBillsVo,transferBillsVo1);
                    transferBillsVo1.setTransferAmount(transferBillsVo.getTransferAmount()-20000);
                    transferBillsVo.setTransferAmount(20000);
                    transferBills(transferBillsVo1);
                }
                transferBills( transferBillsVo);
                });

    }
    @Override
    public void  transferBills(TransferBillsVo transferBillsVo){
        TransferBillsVo transferBills = V3PayUtil.createTransferBills(transferBillsVo);
        JiajiaTransferAccounts jiajiaTransferAccounts=new JiajiaTransferAccounts();
        BeanUtils.copyProperties(transferBills,jiajiaTransferAccounts);
        JSONObject returnJSONObject = transferBills.getReturnJSONObject();
        jiajiaTransferAccounts.setState(returnJSONObject.getString("state"));
        jiajiaTransferAccounts.setTransferAmount(new BigDecimal(transferBills.getTransferAmount()).divide(new BigDecimal("100")).setScale(2,RoundingMode.DOWN));
        jiajiaTransferAccounts.setTransferBillNo(returnJSONObject.getString("transfer_bill_no"));
        jiajiaTransferAccounts.setPackageInfo(returnJSONObject.getString("package_info"));
        jiajiaTransferAccounts.setVersion(LocalDateTime.now()+String.valueOf(Math.random()));
        jiajiaTransferAccounts.setPaymentChannels(transferBillsVo.getPaymentChannels());
        //用户收款操作
        if(jiajiaTransferAccounts.getState().equals("ACCEPTED") ||
                jiajiaTransferAccounts.getState().equals("PROCESSING") ||
                jiajiaTransferAccounts.getState().equals("WAIT_USER_CONFIRM")){
            jiajiaTransferAccounts.setUserStatus("1");
        }
        jiajiaTransferAccounts.setDeleted("1");
        jiajiaTransferAccountsService.insertJiajiaTransferAccounts(jiajiaTransferAccounts);
    }

}
